#!/usr/bin/env perl
use warnings;
use strict;

use DBI;
use CGI;

# change /path/to/includes to match your setup
BEGIN {
    use constant INCLUDES => '/path/to/includes';
    require(INCLUDES . '/functions.pl');
    require(INCLUDES . '/database.pl');
    require(INCLUDES . '/images.pl');
}

# create database connection
my $dbh = DBI->connect(DB_DBI, DB_USER, DB_PASS);

# get cookie data (login credentials)
my $cgi = CGI->new;
my $c_user = $cgi->cookie('user');

# fetch user credentials
my %user = get_user($dbh, $c_user);

# check user credentials
if (not defined($user{'hash'})) {
    $dbh->disconnect;
    error BAD_CREDS;
} elsif (not ($user{'permissions'} & ACCESS_IMG)) {
    $dbh->disconnect;
    error ACCESS_DENIED;
}

# get image id from cgi
my $id;
if (defined($cgi->param('image')) and $cgi->param('image') =~ /^[0-9]+$/) {
    $id = int($cgi->param('image'));
}

if (not defined($id)) {
    $dbh->disconnect;
    error BAD_CGI;
}

# fetch image data from database
my (@data) = get_image_data($dbh, $id);

if (not defined($data[0])) {
    $dbh->disconnect;
    error BAD_CGI;
}

# done with the database connection
$dbh->disconnect;

# display page content
html_begin;
html_title $data[1];
html_css(('images.css'));
html_body;
print_image_view(@data);
html_end;
